import 'dart:io';

import 'package:note/common/common.dart';
import 'package:note/common/tools.dart';
import 'package:note/models/appSetModel.dart';
import 'package:note/models/noteModel.dart';
import 'package:get/get.dart';
import 'package:note/widgets/dialog.dart';
import 'package:package_info_plus/package_info_plus.dart';

import '../common/info.dart';
import 'hiveUtils.dart';

class GlobalUtil {
  static GlobalUtil? _instance;

  GlobalUtil._();

  static final noteList = <Note>[].obs;
  static PackageInfo? packageInfo;
  static final RxInt favoriteNum = 0.obs;
  static final appSet = AppSetModel().obs;

  static GlobalUtil getInstance() {
    _instance ??= GlobalUtil._();
    return _instance!;
  }

  static void setNote(Note note) {
    //保存本地hive
    HiveUtil.noteBox.put(note.id, note);
    //保存到global
    for (int i = 0; i < noteList.length; i++) {
      if (note.id == noteList[i].id) {
        noteList[i] = note;
        sortNote();
        return;
      }
    }
    noteList.add(note);
    sortNote();
  }

  static void sortNote() {
    noteList.sort((a, b) => b.editTime.compareTo(a.editTime));
  }

  static void deleteNote(Note note) {
    Get.dialog(defaultDialog(
        title: Strings.warning,
        content: '你确定要删除此笔记吗?',
        sureFunction: () {
          //刪除图片
          for (final img in note.images) {
            if (File(img).existsSync()) {
              File(img).deleteSync();
            }
          }
          noteList.remove(note);
          HiveUtil.noteBox.delete(note.id);
          Toasts.showToast(Strings.deleted);
          if (note.isFavorite) {
            GlobalUtil.favoriteNum.value--;
          }
          Get.back();
        }));
  }

  static void cleanNote() {
    Get.dialog(defaultDialog(
        title: Strings.warning,
        content: '你确定要删除全部笔记吗?',
        cancelFunction: () {
          Toasts.showToast(Strings.cancel);
        },
        sureFunction: () {
          noteList.clear();
          Directory folder = Directory(FilePath.getNoteImageDirectory);
          if (folder.existsSync()) {
            folder.deleteSync(recursive: true);
            folder.createSync(recursive: true);
          }
          HiveUtil.noteBox.clear();
          favoriteNum.value = 0;
          Toasts.showToast(Strings.deleted);
        }));
  }

  static void getAppSet() {
    var set = HiveUtil.appSetBox.get(Info.appSetKey);
    if (set == null) {
      GlobalUtil.appSet.value.userName = Strings.defaultUserName;
      return;
    }
    appSet.value = set as AppSetModel;
  }

  static void setAppSet(AppSetModel set) {
    appSet.update((val) {
      val?.userName = set.userName;
      if (set.bgImgPath != null) {
        val?.bgImgPath = set.bgImgPath;
      }
    });
    HiveUtil.appSetBox.put(Info.appSetKey, appSet.value);
  }
}
